<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CommentUpdateRequest;
use App\Http\Responses\Response;
use App\Models\Comment;
use Exception;
use Illuminate\Http\JsonResponse;

class CommentController extends Controller
{
    public function list(): JsonResponse
    {
        $comments = Comment::with(["posts", "children"])->get();
        return Response::resource_success($comments);
    }

    public function delete($id): JsonResponse
    {
        $comments = Comment::where("comm_id", $id);
        if ($comments->count() <= 0) {
            return Response::not_found();
        }
        $comment = $comments->get()[0];
        try {
            $comment->delete();
        } catch (Exception $exception) {
            return Response::delete_error();
        }
        return Response::delete_success($comment);
    }

    public function update(CommentUpdateRequest $request, $id)
    {
        $comment = Comment::find($id);
        if (!$comment) {
            return Response::not_found();
        }
        if ($comment->update($request->validated())) {
            return Response::update_success($comment);
        }
        return Response::update_error();
    }

}
